﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
namespace DotNetStar.TheKing.Web.Filters
{
    /// <summary>
    /// 异常过滤器
    /// </summary>
    /// <seealso cref="Microsoft.AspNetCore.Mvc.Filters.ExceptionFilterAttribute" />
    public class ExceptionHandlerAttribute:ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            var result = new ViewResult { ViewName = "Error" };
            result.ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), context.ModelState)
            {
                { "Exception", context.Exception }
            };
            context.Result = result;
            context.ExceptionHandled = true;

            context.HttpContext.Response.Body = context.Exception.Message.ToMemoryStream();
            context.HttpContext.Response.StatusCode = 500;

            context.HttpContext.RequestServices.GetService<ILoggerFactory>()
                .CreateLogger(context.Exception.GetType())
                .LogError(context.Exception, context.Exception.Message);
        }
    }
}
